package com.test.mq;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class Subscriber {

	public static void main(String[] args) throws JMSException {
		TopicConnectionFactory connectionFactory;
		TopicConnection connection = null;
		TopicSession session = null;
		TopicSubscriber subscriber;

		try {
			connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
					ActiveMQConnection.DEFAULT_PASSWORD, "tcp://localhost:61616");
			connection = connectionFactory.createTopicConnection();
			connection.start();
			session = connection.createTopicSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
			Topic topic = session.createTopic("mq.topic");
			subscriber = session.createSubscriber(topic);
			while (true) {
				Message message = subscriber.receive();
				if (null != message && message instanceof TextMessage)
					System.out.println("Receive Message: " + ((TextMessage) message).getText());
				else
					break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (connection != null)
				connection.close();
		}
	}
}